# -*- coding: utf-8 -*-
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# PyPRTG - A Python helper library for PRTG
#
# Copyright (c) 2019 Paessler AG
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""
HTTP Push Data sensor clients.
"""

import urllib.error
import urllib.parse
import urllib.request

import httpx
from httpx._models import Response  #noqa

from prtg_sensors_api.sensor.result import CustomSensorResult
from prtg_sensors_api.ssl import create_ssl_context

__all__ = ["HttpPushDataAdvancedClient"]


class HttpPushDataAdvancedClient(object):
    """
    HTTP Push Data Advanced client.
    """
    __client: httpx.AsyncClient = httpx.AsyncClient()
    _url = None
    _ssl_context = None
    _user_agent = "Paessler AG - PRTG HTTP Push Data Advanced Client"

    @property
    def httpx(self) -> httpx.AsyncClient:
        return type(self).__client

    @property
    def url(self):
        """
        The target URL of the HTTP Push Data Advanced Client.

        @return: The client's target URL.
        @rtype: str
        """
        return self._url

    def __init__(
            self,
            host,
            port,
            token,
            use_ssl=True,
            check_hostname=False,
            allow_self_signed_cert=False,
    ):
        """
        Creates a new instance of the HTTP Push Data Advanced Client.

        @param host: PRTG host name or IP address.
        @type host: str
        @param port: Port number of the target sensor.
        @type port: int or str
        @param token: The PRTG Sensor Token.
        @type token: str
        @param use_ssl: True for secure HTTPS connections, False for
                        insecure HTTP connections. Default is True.
        @type use_ssl: bool
        @param check_hostname: True, when the target host name shall
                               be verified against its certificate
                               upon connection, False, when the target's
                               host name doesn't need to match its
                               certificate. Default is False.
        @type check_hostname: bool
        @param allow_self_signed_cert: True to allow self-signed certificates,
                                       False to enforce a valid certificate
                                       chain. Default is False.
        @type allow_self_signed_cert: bool
        """
        params = {
            "ssl": use_ssl and "s" or "",
            "host": host,
            "port": str(port),
            "token": token,
        }
        self._url = "http%(ssl)s://%(host)s:%(port)s/%(token)s" % params

        if use_ssl:
            self._ssl_context = create_ssl_context(
                allow_self_signed_cert, check_hostname
            )
        else:
            self._ssl_context = None

    def send(self, payload):
        """
        Sends sensor channel data to the configured target URL.

        @param payload: A JSON-formatted custom sensor result.
        @type payload: str

        @return PRTG's response.
        @rtype: str
        """
        data = payload.encode("utf-8")
        headers = {"Content-type": "application/json", "User-Agent": self._user_agent}

        request = urllib.request.Request(self._url, data=data, headers=headers)

        response = urllib.request.urlopen(
            request, timeout=10, context=self._ssl_context
        )

        return response.read()

    async def asend(self, payload: CustomSensorResult) -> Response:
        return await self.httpx.post(url=self._url, json=payload.result)
